package a10_动态规划;

/**
 * <p>
 * a34_买卖股票的最佳时机2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/20
 */
public class a34_买卖股票的最佳时机2 {

    //dp[i][0]：持有
    //i-1天持有：dp[i-1][0]
    //i天买入：dp[i-1][1] - prices[i]

    //dp[i][1]：不持有
    //i-1天卖出：dp[i-1][1]
    //i天卖出：dp[i-1][0] + prices[i]

    //初始化：dp[0][0]=-prices[0] dp[0][1]=0
    public int maxProfit(int[] prices) {
        int[][] dp = new int[prices.length][2];
        dp[0][0]=-prices[0];
        dp[0][1]=0;
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1] - prices[i]);
            dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0] + prices[i]);
        }
        return Math.max(dp[dp.length - 1][0],dp[dp.length - 1][1]);
    }
}
